//
//  WBRefreshControl.m
//  自定义下拉刷新控件
//
//  Created by 韩菲菲 on 16/8/20.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

#import "WBRefreshControl.h"

#define WBRefreshControlH 50

typedef enum : NSUInteger {
    Normal,
    Pulling,
    Refreshing
} WBRefreshControlType;


@interface WBRefreshControl ()

//将要添加到的view
@property (nonatomic , strong) UIScrollView *scrollView;

@property (nonatomic , assign) WBRefreshControlType controlState;


@property (nonatomic , strong) UILabel *label;


@property (nonatomic , strong) UIImageView *imageView;


@property (nonatomic , strong) UIActivityIndicatorView *activityView;

@end


@implementation WBRefreshControl

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:CGRectMake(0, -WBRefreshControlH, [UIScreen mainScreen].bounds.size.width, WBRefreshControlH)])
    {
        
        [self setupUI];
    
    }
    
    return self;

}


- (UIImageView *)imageView
{
    if(!_imageView)
    {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    }
    
    return _imageView;

}

- (UIActivityIndicatorView *)activityView
{
    if(!_activityView)
    {
        
        _activityView = [[UIActivityIndicatorView alloc] init];
    
    }
    
    return _activityView;

}


- (void)setControlState:(WBRefreshControlType)controlState
{
    
    WBRefreshControlType type = self.controlState;
    
    _controlState = controlState;
    
    if (controlState == Pulling)
    {
        self.label.text = @"下拉中";
        
        [UIView animateWithDuration:0.5 animations:^{
           
            self.imageView.transform = CGAffineTransformMakeRotation(M_PI * -3);
        }];
        
    }else if(controlState == Refreshing)
    {
        self.label.text = @"刷新中";
        
        [UIView animateWithDuration:0.5 animations:^{
            
            UIEdgeInsets inset = self.scrollView.contentInset;
            inset.top += WBRefreshControlH;
            self.scrollView.contentInset = inset;
            
        } completion:^(BOOL finished) {
            
            [self.activityView startAnimating];
            
            self.imageView.hidden = YES;
            
            //告诉外界刷新
            [self sendActionsForControlEvents:UIControlEventValueChanged];
            
        }];
        
    }else
    {
        
        self.label.text = @"正常";
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.imageView.transform = CGAffineTransformIdentity;
        }];
        
        
        if(type == Refreshing)
        {
            [UIView animateWithDuration:0.25 animations:^{
                
                UIEdgeInsets inset = self.scrollView.contentInset;
                inset.top -= WBRefreshControlH;
                self.scrollView.contentInset = inset;
                
            } completion:^(BOOL finished) {
                
                [self.activityView stopAnimating];
                self.imageView.hidden = NO;
                
            }];
        }
    
        
    }

}


- (UILabel *)label
{
    if(!_label)
    {
        _label = [[UILabel alloc] init];
        
        _label.text = @"正常";
        
        _label.textColor = [UIColor whiteColor];
        
        _label.font = [UIFont systemFontOfSize:15];
    
    }
    
    return _label;

}


- (void)endRefreshing
{
    self.controlState = Normal;

}

- (void)setupUI
{
    
    self.backgroundColor = [UIColor orangeColor];
    
    //加载控件
    [self addSubview:self.label];
    [self addSubview:self.imageView];
    [self addSubview:self.activityView];
    
    //设置约束
    self.label.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *labelConstraintX = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    [self addConstraint:labelConstraintX];
    
    NSLayoutConstraint *labelConstraintY = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    [self addConstraint:labelConstraintY];
    
    self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *imageViewConstraintX = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:-35];
    [self addConstraint:imageViewConstraintX];
    
    NSLayoutConstraint *imageViewConstraintY = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    [self addConstraint:imageViewConstraintY];
    
    self.activityView.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSLayoutConstraint *activityViewConstraintX = [NSLayoutConstraint constraintWithItem:self.activityView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:-35];
    [self addConstraint:activityViewConstraintX];
    
    NSLayoutConstraint *activityViewConstraintY = [NSLayoutConstraint constraintWithItem:self.activityView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    [self addConstraint:activityViewConstraintY];

}

//该控件要加载到哪个View上面
- (void)willMoveToSuperview:(UIView *)newSuperview
{
    //获取到外面的tableview
    self.scrollView = (UIScrollView *)newSuperview;
    
    //使用KVO监听tableview的滚动
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

}

//移除KVO
- (void)dealloc
{
    [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];

}



//监听回调方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    
    CGFloat top = self.scrollView.contentInset.top;
    
    //手指在拖动
    if (self.scrollView.dragging){
        
        if (self.scrollView.contentOffset.y > -WBRefreshControlH - top && self.controlState == Pulling) {
            NSLog(@"正常");
            self.controlState = Normal;
            
        }else if(self.scrollView.contentOffset.y <= -WBRefreshControlH - top && self.controlState == Normal)
        {
            NSLog(@"下拉中");
            self.controlState = Pulling;
        }
    
    }else
    {
        if(self.controlState == Pulling)
        {
            
            NSLog(@"刷新中");
            self.controlState = Refreshing;
        
        }

    }
}




@end
